package com.xingkeduo.gateway.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.cors.reactive.CorsUtils;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;

import reactor.core.publisher.Mono;

@Configuration
public class CorsConfig implements WebFilter
{
	private static final String ALLOWED_HEADERS = "Access-Control-Allow-Headers, Content-Type, token";
	private static final String ALLOWED_METHODS = "GET, PUT, POST, DELETE";
	private static final String ALLOWED_ORIGIN = "*";
	private static final String MAX_AGE = "18000L";
	private static final String ALL = "*";

	@Override

	public Mono<Void> filter(ServerWebExchange ctx, WebFilterChain chain)
	{

		ServerHttpRequest request = ctx.getRequest();
		String path = request.getPath().value();
		ServerHttpResponse response = ctx.getResponse();

		if ("/favicon.ico".equals(path))
		{
			response.setStatusCode(HttpStatus.OK);
			return Mono.empty();
		}

		if (!CorsUtils.isCorsRequest(request))
			return chain.filter(ctx);

		HttpHeaders headers = response.getHeaders();
		headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, ALLOWED_METHODS);
		headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, request.getHeaders().getOrigin());
		headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, ALLOWED_HEADERS);
		headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
		headers.add(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, ALL);
		headers.add(HttpHeaders.ACCESS_CONTROL_MAX_AGE, MAX_AGE);

		if (request.getMethod() == HttpMethod.OPTIONS)
		{
			response.setStatusCode(HttpStatus.OK);
			return Mono.empty();
		}

		return chain.filter(ctx);
	}
}
